/**
 * Created by tanbingqin on 2019/1/22.
 */
import {messages, getQueryUrlParam} from "share/common";
import React from 'react'
import {connect} from "react-redux";
import { Icon, Popover } from 'antd'
import 'styles/components/template/approve-tag.scss'
import baseService from 'share/base.service'
import expenseReportService from 'containers/expense-report/expense-report.service'
import errorMessage from "share/errorMessage";
import Condition from 'components/condition'
import configureStore from "stores";
const { If } = Condition;

class ApproveTag extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      showApproveConcurrentMark: false,
      showAuditConcurrentMark: false,
      isConcurrentAudit: false
    }
  }

  componentWillMount() {
    const { entityOID, loginUser } = this.props;
    let approverOID = getQueryUrlParam('approverOID');
    let isApprovePending = getQueryUrlParam('approvePending') === 'true';
    isApprovePending && baseService.setApproveTag(entityOID, loginUser.userOID, approverOID).then(response => {
      this.setState({ showApproveConcurrentMark: response.data && response.data.userOID && response.data.userOID !== loginUser.userOID });
    }).catch(e => {
      errorMessage(e.response);
    });
  }

  componentWillReceiveProps(nextProps) {
    const { loginUser } = this.props;
    if(nextProps.approvalChains && nextProps.approvalChains.length) {
      let currentOperator = nextProps.approvalChains.filter(i => i.approverOID === loginUser.userOID);
      //counterSignRule 会签规则   3001 所有审批人通过  3002 任意人审批通过
      let isConcurrentAudit = nextProps.isAuditInApproveStatus && currentOperator.length && currentOperator[0].countersignRule === 3002;
      this.setState({ isConcurrentAudit }, this.getAuditConcurrentMark );
      isConcurrentAudit && window.addEventListener('unload', this.delAuditor)
    }
  }

  componentWillUnmount() {
    const { isConcurrentAudit } = this.state;
    if( isConcurrentAudit ) {
      this.delAuditor();
      window.removeEventListener('unload', this.delAuditor);
    }
  }

  getAuditConcurrentMark = () => {
    const { isConcurrentAudit } = this.state;
    const { entityOID } = this.props;
    isConcurrentAudit && expenseReportService.getAuditConcurrentMark(entityOID).then(res => {
      if(res.data && res.data.auditorSize > 1) {
        this.setState({ showAuditConcurrentMark: true });
      }
    });
  };

  delAuditor = () => {
    const { entityOID } = this.props;
    //异步请求大概率会在页面卸载中被忽略 同步请求可能阻塞导致性能问题 sendBeacon唯一支持Content-Type header  没法塞token啊。。。。
    let client = new XMLHttpRequest();
    client.open("POST", `/api/audit/${entityOID}/flag`, false); // 第三个参数表明是同步的 xhr
    client.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    client.setRequestHeader("Authorization", `Bearer ${this.props.authToken.access_token}`);
    client.send();
    // if (navigator.sendBeacon) {
    //   let headers = {
    //     type: 'application/x-www-form-urlencoded',
    //     Authorization: `Bearer ${this.props.authToken.access_token}`
    //   };
    //   let blob = new Blob([], headers);
    //   let result = navigator.sendBeacon(`/api/audit/${entityOID}/flag`, blob); //result是个bool值代表请求是否排队成功，暂未处理
    // }
  };

  render() {
    const { showApproveConcurrentMark, showAuditConcurrentMark } = this.state;
    const { approvalChains } = this.props;
    let signType = {3001: messages('expense-parent-report.key254')/*所有人*/, 3002: messages('expense-parent-report.key255')/*任意人*/};
    let nodeType = {1001: messages('expense-parent-report.key256')/*审批*/, 1012: messages('expense-parent-report.key257')/*审核*/};
    let nodeName = approvalChains[0] ? nodeType[approvalChains[0].nodeType] : nodeType[1001];
    let signRule = approvalChains[0] ? signType[approvalChains[0].countersignRule] : signType[3002];
    const content = (
      <div style={{width: 210}}>
        <p className='reset-margin-bottom'>{`${messages('expense-parent-report.key258',{arg1: nodeName,arg2: signRule,arg3: nodeName})/*当前{arg1}节点为{arg2}{arg3}通过*/}；`}</p>
        <p className='reset-margin-bottom'>{messages('expense-parent-report.key259',{arg1: nodeName})/*本单据正由其他人{arg1}*/}</p>
      </div>
    );
    return (
      <If value={showApproveConcurrentMark || showAuditConcurrentMark}>
        <div className="audit-concurrent-mark twink">
          <span className="tag-title">{messages('components.key214')/*审批中*/}</span>
          <Popover content={content} placement="bottomRight">
            <Icon type="info-circle" className="tag-icon"/>
          </Popover>
        </div>
      </If>
    )
  }
}

ApproveTag.propTypes = {
  entityOID: React.PropTypes.string //单据oid
};

ApproveTag.defaultProps = {
  entityOID: ''
};

ApproveTag.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    loginUser: state.login.loginUser,
    authToken: state.main.authToken
  }
}

export default connect(mapStateToProps)(ApproveTag);
